//
//  forumViewController.m
//  autoHome
//
//  Created by qianfeng on 15/9/9.
//  Copyright (c) 2015年 qf1523. All rights reserved.
//

#import "forumViewController.h"
#import "JingXuanCell.h"
#import "JingXuanModel.h"
#import "AFHTTPRequestOperationManager.h"
#import "MenuController.h"
#import "HorizontalTableView.h"
#import "FVDetailController.h"
#import "MJRefresh.h"

#define URL @"http://app.api.autohome.com.cn/autov4.8.8/club/jingxuantopic-pm1-c%d-p%d-s30.json"
@interface forumViewController ()<UITableViewDataSource,UITableViewDelegate,freshDelegate>
{
    //主tableView
    
    //数据源数组
    NSMutableArray *_dataArr;
    
    
    //菜单名字数据源
    NSMutableArray *_menuArr;
    
    //横向标题
    UITableView *table;
   
    NSMutableArray *indexArr;
    
    UITableView *_mtableView;
    NSMutableArray *_meArr;
    NSMutableArray *mindexArr;
    int currentIndex;
    BOOL isPull;
    
    //标题下得蓝线
    UIView *blueLine ;
    
    //记录菜单的cell
    UITableViewCell *_cell;

}
@property(nonatomic,assign)NSInteger page;

@property(nonatomic,strong)MenuController *menu;
@end

@implementation forumViewController

+(instancetype)sharedViewCtr
{
    static forumViewController *vCtr;
    if (!vCtr) {
        vCtr = [[forumViewController alloc] init];
    }
    
    return vCtr;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    //设置友盟社会化组件appkey
        _dataArr = [[NSMutableArray alloc]init];
    _cell = [[UITableViewCell alloc] init];    _page = 1;
    isPull = YES;
    currentIndex = 0;
    [self creatUI];
    [self creatDataSourceIndex:currentIndex andPage:_page];
    [self creatNavBar];
    [self creatRefresh];
    
    
}
#pragma mark - 刷新
-(void)creatRefresh
{
    [_tableView addHeaderWithTarget:self action:@selector(pull)];
    [_tableView addFooterWithTarget:self action:@selector(up)];

}
-(void)pull
{
     isPull = YES;
        _page=1;
        [self creatDataSourceIndex:currentIndex andPage:_page];
   
    [_tableView headerEndRefreshing];
}
-(void)up
{
     isPull = NO;
            _page ++;
        [self creatDataSourceIndex:currentIndex andPage:_page];
    
        [_tableView footerEndRefreshing];

}
-(void)creatMenuView
{
    _menu = [[MenuController alloc] init];
    
    _menu.view.frame  = CGRectMake(self.view.frame.size.width, 0, 240, self.view.bounds.size.height-80-49);
    [self.view addSubview:_menu.view];
    _meArr = [[NSMutableArray alloc] init];
    
    NSArray *mArr = @[@"全部",@"汽车之家十年",@"媳妇当车模",@"美人“记”",@"论坛名人堂",@"论坛讲师",@"精挑细选",@"现身说法",@"高端阵地",@"电动车",@"汇买车",@"行车点评",@"超级试驾员",@"海外购车",@"经典老车",@"妹子选车",@"优惠购车",@"原创大片",@"顶配风采",@"改装有理"];
    
    NSArray *aaa = @[@(0),@(233),@(104),@(110),@(172),@(230),@(121),@(106),@(118),@(210),@(199),@(198),@(168),@(113),@(109),@(191),@(196),@(107),@(105),@(122)];
    
    mindexArr = [[NSMutableArray alloc] initWithArray:aaa];
    [_meArr addObjectsFromArray:mArr];
    
    _mtableView = [[UITableView alloc] initWithFrame:CGRectMake(self.view.frame.size.width-240, 64, 240, self.view.frame.size.height-80-30) style:UITableViewStylePlain];
    _mtableView.delegate = self;
    _mtableView.dataSource = self;
    _mtableView.backgroundColor = [UIColor lightGrayColor];
    [self.menu.view addSubview:_mtableView];
    UILabel *headLabel = [[UILabel alloc] init];
    UIView *lineV = [[UIView alloc] initWithFrame:CGRectMake(self.view.frame.size.width-240, 63, 240, 1)];
    lineV.backgroundColor = [UIColor grayColor];
    lineV.alpha = 0.5;
    
    headLabel.frame = CGRectMake(self.view.frame.size.width-240, 0, 240, 64);
    headLabel.backgroundColor = [UIColor whiteColor];
    headLabel.text = @"精选分类";
    headLabel.textAlignment = NSTextAlignmentCenter;
    [self.menu.view addSubview:headLabel];
    [self.menu.view addSubview:lineV];
    
    UIButton *btn = [UIButton buttonWithType:UIButtonTypeSystem];
    btn.frame =CGRectMake(self.view.frame.size.width-45, 20, 40, 30);
    [btn setTitle:@"关闭" forState:UIControlStateNormal];
    btn.userInteractionEnabled = YES;
    [btn setTitleColor:[UIColor blueColor] forState:UIControlStateNormal];
    [btn addTarget:self action:@selector(closeMenu:) forControlEvents:UIControlEventTouchUpInside];
    [self.menu.view addSubview:btn];
    self.menu.view.userInteractionEnabled = YES;
    
 
    
}

-(void)closeMenu:(UIButton*)btn
{
    NSLog(@"close~~");
    
    [UIView animateWithDuration:0.3 animations:^{
        _coverView.alpha = 0.5;
        
        self.menu.view.frame = CGRectMake(self.view.frame.size.width+240, 0, 240, self.view.frame.size.height);
        
    } completion:^(BOOL finished) {
        
    }];
 
    self.menu.isClose = @"y";
}

-(void)refreshTableView:(int)indexpath
{
    [self creatDataSourceIndex:indexpath andPage:1];
    
}
-(void)creatNavBar
{
    self.navigationController.navigationBarHidden = YES;
    UIView *headView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.view.bounds.size.width, 84)];
//    headView.backgroundColor = [UIColor cyanColor];
    NSArray *titleArr = @[@"精选日报",@"常用论坛"];
    for (int i = 0; i<titleArr.count; i++) {
        UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
        btn.titleLabel.font = [UIFont systemFontOfSize:15];
        btn.tag = i +11;
        [btn setTitleColor:[UIColor grayColor] forState:UIControlStateNormal];
        [btn setTitleColor:[UIColor blueColor] forState:UIControlStateSelected];
        [btn setTitle:titleArr[i] forState:UIControlStateNormal];
//        [btn addTarget:self action:@selector(titltBtnClick:) forControlEvents:UIControlEventTouchUpInside];
        btn.frame = CGRectMake(5+i*80, 24, 70, 30);
        [headView addSubview:btn];
        if(btn.tag == 11) {
            btn.selected = YES;
        }
        
    }
    blueLine = [[UIView alloc] initWithFrame:CGRectMake(5, 49, 65, 2)];
    blueLine.backgroundColor = [UIColor blueColor];
    [headView addSubview:blueLine];
    UIView *line = [[UIView alloc] initWithFrame:CGRectMake(0, 50, self.view.frame.size.width, 1)];
    line.backgroundColor = [UIColor lightGrayColor];
    line.alpha = 0.3;
    [headView addSubview:line];
    UIButton *rBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [rBtn setFrame:CGRectMake(self.view.bounds.size.width-30, 24, 25, 25)];
    [rBtn setBackgroundImage:[UIImage imageNamed:@"searchBar_search@2x"] forState:UIControlStateNormal];
//    [rBtn setImage:[UIImage imageNamed:@"searchBar_search@2x"] forState:UIControlStateNormal];
    [headView addSubview:rBtn];
    
    UIView *flowHeadView = [[UIView alloc] initWithFrame:CGRectMake(0, 55, self.view.bounds.size.width, 30)];
    
    flowHeadView.backgroundColor = [UIColor whiteColor];
    [self.view bringSubviewToFront:headView];
    
    [headView addSubview:flowHeadView];
    UIButton *frBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    frBtn.tag = 111;
    frBtn.backgroundColor = [UIColor whiteColor];
    frBtn.frame = CGRectMake(self.view.bounds.size.width-30,0 , 30, 30);
    [frBtn addTarget:self action:@selector(pressBtn:) forControlEvents:UIControlEventTouchUpInside];
    [frBtn setImage:[UIImage imageNamed:@"bar_btn_icon_album@2x.png"] forState:UIControlStateNormal];
    
    [flowHeadView addSubview:frBtn];
    table  = [[UITableView alloc] init];
    table.backgroundColor = [UIColor whiteColor];
    [table.layer setAnchorPoint:CGPointMake(0.0, 0.0)];
    table.transform = CGAffineTransformMakeRotation(M_PI/-2);
    table.showsVerticalScrollIndicator = NO;
    table.delegate = self;
    table.dataSource = self;
    table.frame = CGRectMake(5, 30, self.view.frame.size.width-40, 30);
    table.rowHeight = 60.0;
    NSLog(@"%f,%f,%f,%f",table.frame.origin.x,table.frame.origin.y,table.frame.size.width,table.frame.size.height);
    table.delegate = self;
    table.dataSource = self;
    table.separatorStyle = UITableViewCellSeparatorStyleNone;
    [flowHeadView addSubview:table];
    [self.view addSubview:headView];
    [self loadData];
    UIView *rLine = [[UIView alloc] initWithFrame:CGRectMake(self.view.frame.size.width-35, 3, 1, 24)];
    rLine.backgroundColor = [UIColor lightGrayColor];
    rLine.alpha = 0.3;
    [flowHeadView addSubview:rLine];
   
}


-(void)loadData
{
    _menuArr = [[NSMutableArray alloc] init];
    
    NSArray *mArr = @[@"全部",@"汽车之家十年",@"媳妇当车模",@"美人“记”",@"论坛名人堂",@"论坛讲师",@"精挑细选",@"现身说法",@"高端阵地",@"电动车",@"汇买车",@"行车点评",@"超级试驾员",@"海外购车",@"经典老车",@"妹子选车",@"优惠购车",@"原创大片",@"顶配风采",@"改装有理"];
    
    indexArr = [[NSMutableArray alloc] init];
    
    NSArray *aaa = @[@(0),@(233),@(104),@(110),@(172),@(230),@(121),@(106),@(118),@(210),@(199),@(198),@(168),@(113),@(109),@(191),@(196),@(107),@(105),@(122)];
    [indexArr addObjectsFromArray:aaa];
    [_menuArr addObjectsFromArray:mArr];
    
    [table reloadData];
}

- (void)creatMenu{
    

     _menu = [[MenuController alloc] init];
    
    _menu.view.frame  = CGRectMake(self.view.frame.size.width, 20, 240, self.view.bounds.size.height-80-49);
    [self.view addSubview:_menu.view];
 NSArray *mArr = @[@"全部",@"汽车之家十年",@"媳妇当车模",@"美人“记”",@"论坛名人堂",@"论坛讲师",@"精挑细选",@"现身说法",@"高端阵地",@"电动车",@"汇买车",@"行车点评",@"超级试驾员",@"海外购车",@"经典老车",@"妹子选车",@"优惠购车",@"原创大片",@"顶配风采",@"改装有理"];
    [_menu creatMenuView:mArr];
    // 左侧边栏结束
    
    
}

-(void)viewWillAppear:(BOOL)animated
{
    [_tableView reloadData];
}


-(void)pressBtn:(UIButton*)btn
{
//    self.hidesBottomBarWhenPushed = YES;
    _coverView = [[UIView alloc] initWithFrame:self.view.frame];
    _coverView.backgroundColor = [UIColor grayColor];
    _coverView.alpha = 0.5;
    
    [UIView commitAnimations];
   
    _coverView.tag = 123;
    [self.view addSubview: _coverView];
//    [self creatMenu];
    [self creatMenuView];
    [UIView animateWithDuration:0.3 animations:^{
        
        
        self.menu.view.frame = CGRectMake(0, 0, 240, self.view.frame.size.height);
        
    } completion:^(BOOL finished) {
        
    }];

    UIPanGestureRecognizer *pan = [[UIPanGestureRecognizer alloc]initWithTarget:self action:@selector(panDetected:)];
    
    [self.menu.view addGestureRecognizer:pan];
    
}


-(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
{
    if ([object isMemberOfClass:[self.menu class]]) {
        NSString *new = [change objectForKey:@"new"];
        
        if ([new isEqualToString:@"y"]) {
            UIView *view = (UIView*)[self.view viewWithTag:123];
            [view removeFromSuperview];
            [self.menu removeObserver:self forKeyPath:@"isClose"];
            self.menu = nil;
            
        }
    }
    [self.menu removeObserver:self forKeyPath:@"isClose"];
}
-(void)missView:(NSNotification*)notif
{
    UIView *view = (UIView*)[self.view viewWithTag:123];
    
    view.hidden = YES;
}
- (void)panDetected:(UIPanGestureRecognizer*)pan
{
    
     CGPoint currentP;
    currentP = [pan locationInView:self.view];
    
    [UIView animateWithDuration:0.3 animations:^{
        
        self.menu.view.frame = CGRectMake(self.view.frame.size.width, 0, 240, self.view.frame.size.height);
       
        
    } completion:^(BOOL finished) {
        UIView *view = (UIView*)[self.view viewWithTag:123];
        [view removeFromSuperview];
    }];
//    [self.menu setValue:@"y" forKey:@"isClose"];
//
//    [self.menu addObserver:self forKeyPath:@"isClose" options:NSKeyValueObservingOptionNew | NSKeyValueObservingOptionOld context:nil];
   
}
-(void)creatDataSourceIndex:(int)index andPage:(NSInteger)page
{
    static int mchange = 1;
    NSLog(@"%d%d",currentIndex,(int)page);
    NSMutableArray *newArr = [[NSMutableArray alloc] init];
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
   
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObject:@"text/html"];
    NSLog(@"~~~~%@",[NSString stringWithFormat:URL,currentIndex,(int)page]);
    [manager GET:[NSString stringWithFormat:URL,index,(int)page] parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
        if ([responseObject isKindOfClass:[NSDictionary class]]) {
            NSDictionary *resultDic = responseObject[@"result"];
            NSArray *listArr = resultDic[@"list"];
            for (NSDictionary *deDic in listArr) {
//                NSLog(@"%@",deDic);
                JingXuanModel *model = [[JingXuanModel alloc] init];
                [model setValuesForKeysWithDictionary:deDic];
                [newArr addObject:model];

            }
           
            if (isPull) {
                [_dataArr removeAllObjects];
                //加载完成再把原来的数据源清空换成新的
                [_dataArr addObjectsFromArray:newArr];
                [_tableView reloadData];
            }else
            {
                for (JingXuanModel *model in newArr) {
                    [_dataArr addObject:model];
                }
                [_tableView reloadData];
            }
           
             mchange = currentIndex;
                    }
        
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        
        NSLog(@"~~~ERROR~~%@",error.description);
    }];
}

-(void)creatUI
{
    _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 64, self.view.frame.size.width, self.view.frame.size.height)];
    _tableView.delegate = self;
    _tableView.dataSource = self;
    
    [self.view addSubview:_tableView];
}

#pragma mark - tableView代理
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (tableView ==table) {
        return _menuArr.count;
    }else if (tableView == _mtableView)
    {
        return _meArr.count;
    }
    return _dataArr.count;
}

-(UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (tableView == table) {
        static NSString *CellIdentifier = @"Cell";
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
        if (cell == nil) {
            cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault
                                           reuseIdentifier:CellIdentifier] ;
            cell.selectionStyle = UITableViewCellSelectionStyleGray;
            UILabel *label = [[UILabel alloc] init];
            [cell addSubview:label];
            label.tag = 111;
            label.font = [UIFont systemFontOfSize:15];
            
        }
        UILabel *label = (UILabel *)[cell viewWithTag:111];
        label.transform = CGAffineTransformMakeRotation(M_PI/2);
        label.frame = CGRectMake(0, 0, 30, 110);
        label.textAlignment = NSTextAlignmentCenter;
        label.text =_menuArr[indexPath.row];
//        cell.textLabel.text = _menuArr[indexPath.row];
        return cell;
    }else if(tableView == _mtableView){
    static NSString *ce = @"MC";
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:ce];
        if (cell == nil) {
            cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:ce];
        }
        cell.textLabel.text = _meArr[indexPath.row];
//        cell.accessoryType
        return cell;
    
    }else{
static NSString *str = @"JXCELL";
    
    JingXuanCell *cell = [tableView dequeueReusableCellWithIdentifier:str];
    if (!cell) {
        cell = [[JingXuanCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:str];
    }else
    {
        for (UIView *view  in cell.contentView.subviews) {
            if (view.tag >100) {
                UILabel *label = (UILabel*)[cell.contentView viewWithTag:view.tag];
                [label removeFromSuperview];
                UILabel *lab = [[UILabel alloc] initWithFrame:label.frame];
                [cell.contentView addSubview:lab];
                lab.tag = label.tag;
            }
            
        }
    }
        
    JingXuanModel *model = _dataArr[indexPath.row];

    [cell configUIWithModel:model];
    
    return cell;
    }
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (tableView == table) {
//        NSString *str = _menuArr[indexPath.row];
//        NSInteger w = str.length;
        return 110;
//        return (w+1)*18;
    }else if (tableView == _mtableView)
    {
        return 50;
    }
    return 85.0f;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    if (tableView == _tableView) {
        FVDetailController *dv = [[FVDetailController alloc] init];
       JingXuanModel *model = _dataArr[indexPath.row];
        dv.dtId = model.topicid;
        [self.navigationController pushViewController:dv animated:YES];
        
    }else if (tableView == table)
    {
         if ((indexPath.row+3)<=_menuArr.count) {
        [UIView animateWithDuration:0.3 animations:^{
            
            
            [_tableView  setContentOffset:CGPointZero];
            [_tableView reloadData];
        } completion:^(BOOL finished) {
            
            float a =  (((float)indexPath.row + 1) / (float)_menuArr.count);
            CGPoint q;
            q.y = a*table.contentSize.height -110;
            q.x = table.contentOffset.x;
            [table setContentOffset:q animated:YES];
            
        }];
         }

        if (_tableView.contentOffset.x == 0 &&_tableView.contentOffset.y == 0) {
            currentIndex =[indexArr[indexPath.row] intValue];
            [_tableView headerBeginRefreshing];

            [self creatDataSourceIndex:currentIndex andPage:_page];
        }
       
        
    }else if(tableView == _mtableView)
    {
        [_tableView headerBeginRefreshing];
        _cell.selected = NO;
        
        UIView *view = (UIView*)[self.view viewWithTag:123];
        [view removeFromSuperview];
        currentIndex =[indexArr[indexPath.row] intValue];
        [self creatDataSourceIndex:currentIndex andPage:_page];
        
        [UIView animateWithDuration:0.3 animations:^{
            _coverView.alpha = 0.5;
            
            self.menu.view.frame = CGRectMake(self.view.frame.size.width, 0, 240, self.view.frame.size.height);
            
        } completion:^(BOOL finished) {
            
        }];
        if ((indexPath.row+3)<=_menuArr.count) {
            float a =  (((float)indexPath.row + 1) / (float)_meArr.count);
            
            CGPoint q;
            q.y = a*table.contentSize.height -110;
            q.x = table.contentOffset.x;
            [table setContentOffset:q animated:YES];
            UITableViewCell*ccell = [table cellForRowAtIndexPath:indexPath];
            ccell = [table cellForRowAtIndexPath:indexPath];
            _cell = ccell;
            ccell.selected = YES;
        }else {
            float a =  (((float)_meArr.count-2) / (float)_meArr.count);
            
            CGPoint q;
            q.y = a*table.contentSize.height -110;
            q.x = table.contentOffset.x;
            [table setContentOffset:q animated:YES];
            UITableViewCell*ccell = [table cellForRowAtIndexPath:indexPath];
            ccell = [table cellForRowAtIndexPath:indexPath];
            _cell = ccell;
        
        }

    }
}

-(void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    if (scrollView == table) {
        NSLog(@"%f%f",table.contentOffset.x,table.contentOffset.y);
    }
    
}
@end
